
//_mSvgEnabled = true;
//_mSvgForced  = true;

var poly = [];
var routeLine = null;
var routeMarkers = [];
var map = null;

$(document).ready(function(){
    map = new GMap2($("#map_canvas").get(0));    
    
    var mapcenter = $("#map_center").val();
    
    if (mapcenter) {
        var latlong = mapcenter.split(",");
        var zoom = Number($("#map_zoom").val());
        map.setCenter(new GLatLng(latlong[0] ,latlong[1]), zoom);
        loadMarkers();
    } else {
            if (google.loader.ClientLocation) {
                map.setCenter(new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 16);
            } else {
                map.setCenter(new GLatLng(37.4419, -122.1419), 1);
            }
    }   

    map.addControl(new GMapTypeControl());
    map.addControl(new GSmallMapControl());
    map.addControl(new ZoomToFitControl());

    
    GEvent.addListener(map,"click", function(overlay,latlong) {
        addMarker(routeMarkers.length,latlong);
        drawRoute();
    });
    
    GEvent.addListener(map,"singlerightclick", function(latlong,src,overlay) {
        if (overlay) {
            for(var i=0;i<routeMarkers.length;i++) {
                if (overlay == routeMarkers[i]) {
                    routeMarkers.splice(i,1);
                    break;
                }
            }            
            map.removeOverlay(overlay);
            drawRoute();
        }        
    });
    
    GEvent.addListener(map,"moveend", function() {
        $("#map_center").val(map.getCenter().toUrlValue());
    });
    
    GEvent.addListener(map,"zoomend", function(oldzoom, newzoom) {
        $("#map_zoom").val(newzoom);
    });
    
    $("#save_map").validate({
    	 submitHandler: function(form) {
    	   form.submit();
    	 }
    });
    
    $("#email_map").validate({
   	 submitHandler: function(form) {
   	   form.submit();
   	 }
   });

    
});

function addMarker(index, latlong) {
    routeMarkers[index] = new GMarker(latlong,{draggable: true});
    map.addOverlay(routeMarkers[index] );
    GEvent.addListener(routeMarkers[index] , "dragend", drawRoute);
}

function drawRoute() {
    var cMetersToMiles = 0.000621371192;

    if (routeLine != null) {
        map.removeOverlay(routeLine);
    }
    
    poly = [];    
    $(routeMarkers).each(function(i,marker){
        if (i == 0 || i == routeMarkers.length -1) {
            marker.show();
        } else {
            marker.hide();
        }
        poly.push(marker.getLatLng());
    });
    
    var routeLength = 0;

    if (poly.length > 1) {
        routeLine = new GPolyline(poly,'#FF0000', 3, 1);
        map.addOverlay(routeLine);
        routeLine.enableEditing();
    
        GEvent.addListener(routeLine, "lineupdated", updateRoute);

        var markerString = '';
        for(var i=0;i<poly.length;i++) {
            markerString += poly[i].toUrlValue() + ";";
        }
        // Take off last ";" to split later
        markerString = markerString.substring(0,markerString.length-1);
        $("#map_markers").val(markerString);
        
        routeLength = (routeLine.getLength()*cMetersToMiles);
    } else {
    	$("#map_markers").val(';');
    }
    
    $("#map_center").val(map.getCenter().toUrlValue());
    $("#map_zoom").val(map.getZoom());
    $("#route_length").text (routeLength.toPrecision(4) + " miles");
}

function updateRoute() {    
   $(routeMarkers).each(function(i,marker){
        map.removeOverlay(marker);
    });
    
    routeMarkers = [];
    for(var i=0;i<routeLine.getVertexCount();i++) {
        addMarker(i , routeLine.getVertex(i));
    }
    drawRoute();
}

function loadMarkers() {
    var markerString = $("#map_markers").val();
    // Take off last ";" to split later
    markerString = markerString.substring(0,markerString.length-1);
    var markerlist = markerString.split(";");
    
    for(var i=0;i<markerlist.length;i++) {
        var latlong = markerlist[i].split(",");        
        addMarker(i, new GLatLng(latlong[0] ,latlong[1]));
    }
    drawRoute();
}

function ZoomToFitControl() {
}

ZoomToFitControl.prototype = new GControl();

ZoomToFitControl.prototype.initialize = function(map) {
    var container = document.createElement("div");

    var zoomDiv = document.createElement("div");
    this.setButtonStyle_(zoomDiv);
    container.appendChild(zoomDiv);
    zoomDiv.appendChild(document.createTextNode("Fit Route"));
    GEvent.addDomListener(zoomDiv, "click", function() {
    fitRoute();
    });

    map.getContainer().appendChild(container);
    return container;
};

ZoomToFitControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7,7));
};

// Sets the proper CSS for the given button element.
ZoomToFitControl.prototype.setButtonStyle_ = function(button) {
    button.style.textDecoration = "none";
    button.style.color = "black";
    button.style.backgroundColor = "white";
    button.style.font = "arial";
    button.style.fontSize = "14px";
    button.style.border = "2px solid black";
    button.style.padding = "2px";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "6em";
    button.style.cursor = "pointer";
};

function fitRoute() {
    var bounds = new GLatLngBounds();
    for(var i=0;i<routeMarkers.length;i++) {
        bounds.extend(routeMarkers[i].getPoint())
    }
    var lngCenter = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
    var latCenter = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
    var center = new GLatLng(latCenter,lngCenter);
    map.setCenter(center, map.getBoundsZoomLevel(bounds));
    drawRoute();
};

